package ljl.codetop;

import java.util.HashMap;
import java.util.Map;

/**
 * 和为 k 的连续的子数组的个数
 */
public class _560_subarray_sum {

    static class sb {
        /*
         * 计算出每个位置为结束的子数组的和，然后两个 for 循环？找？
         */
        public int subarraySum(int[] nums, int k) {
            int[] sums = new int[nums.length + 1];
            for (int i = 1; i < sums.length; i++) {
                sums[i] += sums[i - 1] + nums[i - 1];
            }
            int res = 0;
            for (int i = 0; i < sums.length; i++) {
                for (int j = i + 1; j < sums.length; j++) {
                    if (sums[j] - sums[i] == k) res++;
                }
            }
            return res;
        }
    }

    static class official1 {
        public int subarraySum(int[] nums, int k) {
            int res = 0;
            for (int i = 0; i < nums.length; i++) {
                int sum = 0;
                for (int j = i; j < nums.length; j++) {
                    sum += nums[j];
                    if (sum == k)
                        res++;
                }
            }
            return res;
        }
    }

    static class official2 {
        public int subarraySum(int[] nums, int k) {
            Map<Integer, Integer> map = new HashMap<>();
            map.put(0, 1);
            int res = 0;
            int prev = 0;
            for (int num : nums) {
                prev += num;
                if (map.containsKey(prev - k)) {
                    res += map.get(prev - k);
                }
                map.put(prev, map.getOrDefault(prev, 0) + 1);
            }
            return res;
        }
    }
}
